﻿/*----------------------------------------------------------------
// Copyright (C) 2014 苏州麦迪斯顿医疗科技股份有限公司
// 文件名：NetworkAddressTable.cs
// 文件功能描述：NetworkAddressTable
// 创建标识：顾伟伟-2014-04-03
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using CPOE.Framework.Configuration;

namespace CPOE.Framework.Throttling
{
    /// <summary>
    /// 网络服务器地址表，用于从配制文件中读取地址列表，随机选择一个地址，替换终结地址uri占位符，
    /// </summary>
   public abstract class NetworkAddressTable
    {
       static List<NetworkAddress> _address = null;

       static Random _random = new Random();

       static NetworkAddressTable()
       {
           //从客户端配制文件中读取服务器地址
           var section = ConfigurationManager.GetSection(AddressConfigurationSection.SectionName) as AddressConfigurationSection;
           if (null == section)
               throw new ConfigurationErrorsException("App.config中未读取到名为addressSection的配制块");

           _address = new List<NetworkAddress>();

           foreach(AddressConfigurationElement element in section.Addresses)
           {
               _address.Add(new NetworkAddress { IsAlive = true, Name = element.Name, ServerIp = element.Value });
           }

           if (_address.Count == 0)
               throw new ConfigurationErrorsException("App.config中未读取到可用的服务器地址");
       }
       /// <summary>
       /// 随机获取一个可用的服务器终结点地址
       /// </summary>
       /// <param name="uri"></param>
       /// <returns></returns>
       public static string GetRandomAddress(string uri)
       {
           if (!uri.Contains(NetworkAddress.ServerIpPlaceHolder))
               throw new ConfigurationErrorsException(string.Format("{0}中不存在服务器地址占位符:{1}", uri, NetworkAddress.ServerIpPlaceHolder));

           if (_address.Count == 0)
               throw new InvalidOperationException("无法连接到服务器，请检查网络设置");

           var index = _random.Next(0, _address.Count - 1);
           return uri.Replace(NetworkAddress.ServerIpPlaceHolder, _address[index].ServerIp);
        
       }
       /// <summary>
       /// 设置服务地址不可用
       /// </summary>
       /// <param name="address"></param>
       public static void SetServerNotAlive(string serverIp)
       {
          var server= _address.FirstOrDefault(i => i.ServerIp == serverIp);

          if (server != null)
              _address.Remove(server);
       }
       /// <summary>
       /// 获取可用的服务器地址列数长度
       /// </summary>
       public static int Count
       {
           get
           {
               return _address.Count;
           }
       }
       /// <summary>
       /// 获取网络服务器地址表
       /// </summary>
       public static List<NetworkAddress> NetworkAddresses
       {
           get
           {
               return _address;
           }
       }
    }
}
